function [s X] = dsc (file, clim, E, X)

   ## usage:  [s X] = dsc (file, clim, E, X)
   ##
   ## downscale "file", using climatology clim and model E

   global PAR PRSV isANA isCUR SDIR ;
   cdata = strrep(SDIR, PAR.sim{:}) ;

   if (nargin < 4 || isempty(X))
      load(file) ;
      printf("dsc: <-- %s\n", file) ;
      X = PC ;
   endif

   ## downscale X using (seasonal) E
   s = do_dsc(X, E) ;

   ## normalize wrt. base climate
   if !isempty(PAR.pddadj) && (!isANA || PAR.anaadj)
      pfile = fullfile(cdata, PAR.pdd, "adj.ob") ;
      if isCUR
	 I = sdate(s.id, PAR.cper(1,:), PAR.cper(2,:)) ;
	 PRSV = strcmp(PAR.pddadj, "preserve") ;
	 adj = feval(PAR.adjfun, s.z(I,:)) ;
	 PRSV = false ;
	 save(pfile, "adj") ;
	 printf("dsc: --> %s\n", pfile) ;
      endif
      load(pfile) ;
      printf("dsc: <-- %s\n", pfile) ;
      s.z = feval(PAR.adjfun, s.z, adj) ;
   endif

   s = rescale(s, "z") ;

   s = pre_pare(s, "inv") ;

endfunction


function s = do_dsc (X, E)

   ## usage: s = do_dsc (X, E)
   ## 
   ## 

   global PAR BATCH
   persistent nprint = 0
   nprint++ ;

   s.id = X.id ;
   s.cal = X.cal ;
   s.z = nan(rows(X.x), size(E, 2)) ;

   for is = 1:length(PAR.ssn)
      I = selssn(PAR.ssn{is}, X.id) ;
      s.z(I,:) = nanmult(X.x(I,:), E(:,:,is)) ;
   endfor
   nc = columns(s.z) ;

   n = ceil(sqrt(nc)) ;

   if PAR.dbg
      if BATCH
	 graphics_toolkit gnuplot ; figure("visible", "off") ;
      endif
      for j=1:nc
	  subplot(n, n, j) ;
	  [f x] = hist(s.z(:,j), 50, 1) ;
	  plot(x, f) ;
	  pause(5) ;
      endfor
      print(pfile = fullfile(fileparts(PAR.mfile), ["pdf_" num2str(nprint) ".png"])) ;
      printf("dsc: --> %s\n", pfile) ;
   endif

endfunction
